using Toolbox.Forms;
using Toolbox.Model;

namespace Toolbox
{
    public partial class MainForm : Form
    {

        // 保存上一次窗口高度，用于计算高度变化
        private int _previousHeight;

        // 关闭窗口行为枚举
        public enum CloseWindowActionEnum
        {
            AskEveryTime = 0, // 每次询问
            MinimizeToTray = 1, // 系统托盘
            ExitProgram = 2 // 退出程序
        }

        // 属性访问器
        public CloseWindowActionEnum CloseWindowAction { get; set; } = CloseWindowActionEnum.AskEveryTime;

        // 控件声明
        private NotifyIcon _notifyIcon = null!;
        private ContextMenuStrip _contextMenu = null!;
        private CustomTabControl _mainTabControl = null!;
        public TextBox LogTextBox { get; set; } = null!;

        public MainForm()
        {
            // 初始化页签注册系统
            TabRegistry.Initialize();

            InitializeCustomComponents();
        }

        private void InitializeCustomComponents()
        {
            // 窗体设置
            Text = "我的工具箱";
            Size = new Size(530, 450);
            // 设置窗口最小尺寸
            MinimumSize = new Size(530, 450);
            StartPosition = FormStartPosition.CenterScreen;
            FormBorderStyle = FormBorderStyle.Sizable;
            MaximizeBox = false;
            // 显式设置窗口图标，使用32x32尺寸的图标
            Icon = LoadIconBySize(32);

            // 初始化系统托盘
            InitializeTrayIcon();

            // 创建主选项卡控件
            _mainTabControl = new CustomTabControl
            {
                Dock = DockStyle.Fill,
                Name = "mainTabControl",
                Padding = new Point(10, 5),
                AllowDrop = true // 允许拖放操作
            };

            // 添加页签切换事件处理
            _mainTabControl.SelectedIndexChanged += (s, e) =>
            {
                // 获取当前选中的页签
                if (_mainTabControl.SelectedTab != null)
                {
                    // 获取页签对应的BaseTabPage实例
                    BaseTabPage? tabPage = _mainTabControl.GetTabPageMapping(_mainTabControl.SelectedTab);
                    // 调用页签的OnTabSelected方法
                    tabPage?.OnTabSelected(this);
                }
            };

            Controls.Add(_mainTabControl);

            // 使用循环创建所有页签（已按顺序排序）
            _mainTabControl.CreateAllTabs();

            // 初始化窗口高度
            _previousHeight = Height;

            // 窗口大小变化事件
            ResizeEnd += (s, e) =>
            {
                int heightChange = Height - _previousHeight;
                if (heightChange != 0)
                {
                    _mainTabControl.NotifyTabsOfHeightChange(Height);
                    _previousHeight = Height;
                }
            };
        }

        // 根据尺寸加载合适的图标
        private Icon LoadIconBySize(int size)
        {
            try
            {
                // 根据需要的尺寸选择最合适的图标文件
                string iconPath = size switch
                {
                    16 => Path.Combine(Application.StartupPath, "Ico", "16.ico"),
                    24 => Path.Combine(Application.StartupPath, "Ico", "24.ico"),
                    32 => Path.Combine(Application.StartupPath, "Ico", "32.ico"),
                    48 => Path.Combine(Application.StartupPath, "Ico", "48.ico"),
                    64 => Path.Combine(Application.StartupPath, "Ico", "64.ico"),
                    72 => Path.Combine(Application.StartupPath, "Ico", "72.ico"),
                    96 => Path.Combine(Application.StartupPath, "Ico", "96.ico"),
                    _ => Path.Combine(Application.StartupPath, "Ico", "128.ico"),
                };

                // 检查图标文件是否存在，如果不存在则返回默认图标
                if (File.Exists(iconPath))
                {
                    return new Icon(iconPath);
                }
                else
                {
                    // 如果找不到指定尺寸的图标，返回应用程序默认图标
                    return Icon ?? SystemIcons.Application;
                }
            }
            catch (Exception)
            {
                // 发生异常时返回默认图标
                return SystemIcons.Application;
            }
        }

        private void InitializeTrayIcon()
        {
            _contextMenu = new ContextMenuStrip();
            _ = _contextMenu.Items.Add("显示窗口", null, (s, e) => ShowMainWindow());
            _ = _contextMenu.Items.Add("-");
            _ = _contextMenu.Items.Add("退出", null, (s, e) => Application.Exit());

            _notifyIcon = new NotifyIcon
            {
                // 为托盘使用32x32尺寸的图标
                Icon = LoadIconBySize(32),
                Text = "我的工具箱",
                ContextMenuStrip = _contextMenu,
                Visible = true
            };

            _notifyIcon.DoubleClick += (s, e) => ShowMainWindow();

            // 初始化上一次窗口高度
            _previousHeight = Height;

            Resize += (s, e) =>
            {
                if (WindowState == FormWindowState.Minimized)
                {
                    Hide();
                    _notifyIcon.ShowBalloonTip(1000, "我的工具箱", "程序已最小化到系统托盘", ToolTipIcon.Info);
                }
                else if (WindowState is FormWindowState.Normal or FormWindowState.Maximized)
                {
                    // 计算窗口高度变化
                    int heightChange = Height - _previousHeight;

                    // 如果高度发生显著变化，通知所有页签
                    if (Math.Abs(heightChange) > 10)  // 增加阈值，避免微小变化也触发
                    {
                        _mainTabControl.NotifyTabsOfHeightChange(Height);
                        _previousHeight = Height;
                    }
                }
            };
        }

        private void ShowMainWindow()
        {
            Show();
            WindowState = FormWindowState.Normal;
            BringToFront();
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                if (CloseWindowAction == CloseWindowActionEnum.AskEveryTime)
                {
                    // 显示询问对话框
                    Form messageBox = new()
                    {
                        Text = "询问",
                        Size = new Size(300, 150),
                        StartPosition = FormStartPosition.CenterParent,
                        FormBorderStyle = FormBorderStyle.FixedDialog,
                        MaximizeBox = false,
                        MinimizeBox = false
                    };

                    Label label = new()
                    {
                        Text = "关闭窗口后要执行什么操作？",
                        Location = new Point(20, 20),
                        Size = new Size(250, 40),
                        TextAlign = ContentAlignment.MiddleCenter
                    };
                    messageBox.Controls.Add(label);

                    Button toTrayButton = new()
                    {
                        Text = "到托盘",
                        Location = new Point(40, 70),
                        DialogResult = DialogResult.Yes
                    };
                    messageBox.Controls.Add(toTrayButton);

                    Button exitButton = new()
                    {
                        Text = "退出",
                        Location = new Point(160, 70),
                        DialogResult = DialogResult.No
                    };
                    messageBox.Controls.Add(exitButton);

                    messageBox.AcceptButton = toTrayButton;
                    // 不设置CancelButton，以便点击X按钮时返回DialogResult.Cancel
                    // messageBox.CancelButton = exitButton;

                    DialogResult result = messageBox.ShowDialog();

                    if (result == DialogResult.Yes) // 到托盘
                    {
                        e.Cancel = true;
                        Hide();
                        _notifyIcon.Visible = true;
                    }
                    else if (result == DialogResult.Cancel)
                    {
                        // 点击X按钮(DialogResult.Cancel)时，不关闭主窗口，不退出程序
                        e.Cancel = true;
                    }
                }
                else if (CloseWindowAction == CloseWindowActionEnum.MinimizeToTray)
                {
                    e.Cancel = true;
                    Hide();
                    _notifyIcon.Visible = true;
                }
            }

            // 如果不是取消关闭操作，释放所有资源
            if (!e.Cancel)
            {
                // 停止所有页签的运行并释放资源
                foreach (TabPage tabPage in _mainTabControl.TabPages)
                {
                    try
                    {
                        BaseTabPage? tabPageImpl = _mainTabControl.GetTabPageMapping(tabPage);
                        tabPageImpl?.StopRunning(this);
                    }
                    catch (Exception ex)
                    {
                        // 记录异常但继续处理其他页签
                        LogTextBox?.AppendText($"释放{tabPage.Text}页签资源时出错: {ex.Message}\r\n");
                    }
                }

                // 只有在真正退出程序时才释放托盘图标资源
                _notifyIcon?.Dispose();
            }

            base.OnFormClosing(e);
        }

    }
}